package com.xiaoma.mvi

import android.os.Bundle
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.lifecycle.lifecycleScope
import com.xiaoma.mvi.databinding.FragmentFlowAnimBinding
import com.xiaoma.mvi.func.BindingFragment
import com.xiaoma.mvi.func.animFlow
import kotlinx.coroutines.launch

class FlowAnimFragment : BindingFragment<FragmentFlowAnimBinding>() {

    private suspend fun transitionAnim() {
        val interpolator = AccelerateDecelerateInterpolator()
        animFlow(0F, 100F, 75, interpolator = interpolator)
            .collect { binding.vShape.translationY = it }
        animFlow(100F, -100F, 150, interpolator = interpolator)
            .collect { binding.vShape.translationY = it }
        animFlow(-100F, 0F, 75, interpolator = interpolator)
            .collect { binding.vShape.translationY = it }
    }

    private suspend fun scaleAnim() {
        animFlow(1F, 3F).collect {
            binding.vShape.scaleX = it
            binding.vShape.scaleY = it
        }
        animFlow(3F, 1F).collect {
            binding.vShape.scaleX = it
            binding.vShape.scaleY = it
        }
    }

    private suspend fun rotationAnim() {
        animFlow(0F, 360F).collect {
            binding.vShape.rotationX = it
        }
        animFlow(0F, 360F).collect {
            binding.vShape.rotationY = it
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.btnTransition.setOnClickListener {
            viewLifecycleOwner.lifecycleScope.launch {
                transitionAnim()
            }
        }

        binding.btnScale.setOnClickListener {
            viewLifecycleOwner.lifecycleScope.launch {
                scaleAnim()
            }
        }

        binding.btnCombine.setOnClickListener {
            viewLifecycleOwner.lifecycleScope.launch {
                launch { scaleAnim() }
                launch { rotationAnim() }
            }
        }

        binding.btnRotation.setOnClickListener {
            viewLifecycleOwner.lifecycleScope.launch {
                rotationAnim()
            }
        }
    }

}